<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>药品管理系统</title>
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    body {
      font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
      background-color: #f5f7fa;
      color: #606266;
    }
    .app-container {
      min-height: 100vh;
      display: flex;
      flex-direction: column;
    }
    .header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 15px 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .logo-area {
      display: flex;
      align-items: center;
    }
    .logo {
      width: 50px;
      height: 50px;
      margin-right: 15px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      font-weight: bold;
    }
    .system-name {
      font-size: 22px;
      font-weight: bold;
    }
    .nav-menu {
      display: flex;
      background-color: #304156;
      padding: 0 20px;
    }
    .nav-item {
      padding: 15px 20px;
      color: #bfcbd9;
      cursor: pointer;
      transition: all 0.3s;
    }
    .nav-item:hover, .nav-item.active {
      color: #409EFF;
      background-color: #263445;
      border-bottom: 2px solid #409EFF;
    }
    .main-content {
      flex: 1;
      padding: 20px;
    }
    .card-container {
      background: white;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      padding: 20px;
    }
    .toolbar {
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .search-area {
      display: flex;
      align-items: center;
    }
    .table-container {
      margin-top: 20px;
    }
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
    .role-tag {
      padding: 0 10px;
      height: 32px;
      line-height: 30px;
      border-radius: 4px;
      font-size: 12px;
    }
    .role-admin {
      background-color: #f0f9eb;
      color: #67c23a;
      border: 1px solid #e1f3d8;
    }
    .role-sales {
      background-color: #ecf5ff;
      color: #409eff;
      border: 1px solid #d9ecff;
    }
    .role-inventory {
      background-color: #fdf6ec;
      color: #e6a23c;
      border: 1px solid #faecd8;
    }
    .footer {
      text-align: center;
      padding: 15px 0;
      color: #909399;
      font-size: 14px;
      background-color: #f5f7fa;
      border-top: 1px solid #e6e6e6;
    }
    .virtual-link {
      color: #909399;
      cursor: not-allowed;
    }
  </style>
</head>
<body>
<div id="app" class="app-container">
  <header class="header">
    <div class="logo-area">
      <div class="logo">药</div>
      <div class="system-name">药品管理系统</div>
    </div>
    <div>
      <el-dropdown @command="handleUserCommand">
                    <span class="el-dropdown-link" style="color: white; cursor: pointer;">
                        {{ currentUser.username }} ({{ formatRole(currentUser.role) }})<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="profile">个人信息</el-dropdown-item>
          <el-dropdown-item command="logout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </header>

  <nav class="nav-menu">
    <div class="nav-item" :class="{active: activeNav === 'dashboard'}" @click="activeNav = 'dashboard'">首页</div>
    <div class="nav-item virtual-link" :class="{active: activeNav === 'medicine'}">药品管理 (虚拟)</div>
    <div class="nav-item virtual-link" :class="{active: activeNav === 'inventory'}">库存管理 (虚拟)</div>
    <div class="nav-item virtual-link" :class="{active: activeNav === 'sale'}">销售管理 (虚拟)</div>
    <div class="nav-item" :class="{active: activeNav === 'user'}" @click="activeNav = 'user'; loadUserList();">用户管理</div>
    <div class="nav-item virtual-link" :class="{active: activeNav === 'report'}">统计报表 (虚拟)</div>
  </nav>

  <main class="main-content">
    <div class="card-container">
      <div class="toolbar">
        <h2>用户管理</h2>
        <div class="search-area">
          <el-input v-model="searchKeyword" placeholder="输入用户名搜索" style="width: 200px; margin-right: 10px;" clearable @clear="loadUserList" @keyup.enter.native="handleSearch"></el-input>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </div>
      </div>

      <div class="toolbar">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddUser" v-if="currentUser.role === 'admin'">添加用户</el-button>
        <el-button type="danger" icon="el-icon-delete" :disabled="selectedUsers.length === 0" @click="handleBatchDelete" v-if="currentUser.role === 'admin'">批量删除</el-button>

        <el-radio-group v-model="filterRole" @change="loadUserList">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button label="admin">管理员</el-radio-button>
          <el-radio-button label="sales">销售员</el-radio-button>
          <el-radio-button label="inventory">库存管理员</el-radio-button>
        </el-radio-group>
      </div>

      <div class="table-container">
        <el-table :data="userList" border stripe v-loading="loading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" v-if="currentUser.role === 'admin'"></el-table-column>
          <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
          <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
          <el-table-column prop="role" label="角色" width="120">
            <template slot-scope="scope">
              <span :class="['role-tag', 'role-' + scope.row.role]">{{ formatRole(scope.row.role) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createtime" label="创建时间" width="180">
            <template slot-scope="scope">{{ formatDate(scope.row.createtime) }}</template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.row)" v-if="currentUser.role === 'admin'">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)" v-if="currentUser.role === 'admin'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"></el-pagination>
      </div>
    </div>
  </main>

  <footer class="footer">© 2023 药品管理系统 - 版权所有</footer>

  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
    <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!userForm.id">
        <el-input v-model="userForm.password" type="password" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="userForm.role" placeholder="请选择角色" style="width: 100%;">
          <el-option label="管理员" value="admin"></el-option>
          <el-option label="销售员" value="sales"></el-option>
          <el-option label="库存管理员" value="inventory"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitUserForm">确 定</el-button>
            </span>
  </el-dialog>
</div>

<script>
  new Vue({
    el: '#app',
    data() {
      return {
        activeNav: 'user',
        currentUser: { id: null, username: '', role: '' },
        userList: [],
        selectedUsers: [],
        searchKeyword: '',
        filterRole: '',
        loading: false,
        pagination: { currentPage: 1, pageSize: 10, total: 0 },
        dialogVisible: false,
        dialogTitle: '添加用户',
        userForm: { id: null, username: '', password: '', role: '' },
        userRules: {
          username: [ { required: true, message: '请输入用户名', trigger: 'blur' }, { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' } ],
          password: [ { required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' } ],
          role: [ { required: true, message: '请选择角色', trigger: 'change' } ]
        }
      };
    },
    mounted() {
      this.loadCurrentUser();
      this.loadUserList();
    },
    methods: {
      loadCurrentUser() {
        const savedUser = localStorage.getItem('currentUser');
        if (savedUser) {
          this.currentUser = JSON.parse(savedUser);
        } else {
          axios.get('/pms/user/current').then(response => {
            if (response.data.success) {
              this.currentUser = response.data.data;
              localStorage.setItem('currentUser', JSON.stringify(response.data.data));
            } else {
              window.location.href = 'login.html';
            }
          }).catch(() => {
            window.location.href = 'login.html';
          });
        }
      },

      loadUserList() {
        this.loading = true;
        axios.get('/pms/user/list').then(response => {
          if (response.data.success) {
            this.userList = response.data.data;
            this.pagination.total = this.userList.length;
            if (this.searchKeyword) {
              this.userList = this.userList.filter(user => user.username.includes(this.searchKeyword));
            }
            if (this.filterRole) {
              this.userList = this.userList.filter(user => user.role === this.filterRole);
            }
          } else {
            this.$message.error(response.data.message);
          }
          this.loading = false;
        }).catch(error => {
          console.error('加载用户列表失败:', error);
          this.$message.error('加载用户列表失败');
          this.loading = false;
        });
      },

      handleSearch() {
        this.pagination.currentPage = 1;
        this.loadUserList();
      },

      handleAddUser() {
        this.dialogTitle = '添加用户';
        this.userForm = { id: null, username: '', password: '', role: '' };
        this.dialogVisible = true;
        if (this.$refs.userForm) this.$refs.userForm.clearValidate();
      },

      handleEdit(user) {
        this.dialogTitle = '编辑用户';
        this.userForm = { id: user.id, username: user.username, password: '', role: user.role };
        this.dialogVisible = true;
        if (this.$refs.userForm) this.$refs.userForm.clearValidate();
      },

      submitUserForm() {
        this.$refs.userForm.validate((valid) => {
          if (valid) {
            if (this.userForm.id) {
              axios.put('/pms/user/update', this.userForm).then(response => {
                if (response.data.success) {
                  this.$message.success(response.data.message);
                  this.dialogVisible = false;
                  this.loadUserList();
                } else {
                  this.$message.error(response.data.message);
                }
              }).catch(error => {
                console.error('更新用户失败:', error);
                this.$message.error('更新用户失败');
              });
            } else {
              axios.post('/pms/user/add', this.userForm).then(response => {
                if (response.data.success) {
                  this.$message.success(response.data.message);
                  this.dialogVisible = false;
                  this.loadUserList();
                } else {
                  this.$message.error(response.data.message);
                }
              }).catch(error => {
                console.error('添加用户失败:', error);
                this.$message.error('添加用户失败');
              });
            }
          }
        });
      },

      handleDelete(userId) {
        this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
        }).then(() => {
          axios.delete(`/pms/user/delete/${userId}`).then(response => {
            if (response.data.success) {
              this.$message.success(response.data.message);
              this.loadUserList();
            } else {
              this.$message.error(response.data.message);
            }
          }).catch(error => {
            console.error('删除用户失败:', error);
            this.$message.error('删除用户失败');
          });
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      },

      handleBatchDelete() {
        if (this.selectedUsers.length === 0) {
          this.$message.warning('请选择要删除的用户');
          return;
        }

        this.$confirm(`此操作将永久删除选中的 ${this.selectedUsers.length} 个用户, 是否继续?`, '提示', {
          confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
        }).then(() => {
          const deletePromises = this.selectedUsers.map(user => axios.delete(`/pms/user/delete/${user.id}`));
          Promise.all(deletePromises).then(responses => {
            const successCount = responses.filter(resp => resp.data.success).length;
            this.$message.success(`成功删除 ${successCount} 个用户`);
            this.loadUserList();
            this.selectedUsers = [];
          }).catch(error => {
            console.error('批量删除用户失败:', error);
            this.$message.error('批量删除用户失败');
          });
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      },

      handleSelectionChange(selection) {
        this.selectedUsers = selection;
      },

      handleSizeChange(size) {
        this.pagination.pageSize = size;
        this.loadUserList();
      },

      handleCurrentChange(page) {
        this.pagination.currentPage = page;
        this.loadUserList();
      },

      handleUserCommand(command) {
        if (command === 'profile') {
          window.location.href = 'personal.html'; // 跳转到个人信息页面
        } else if (command === 'logout') {
          this.handleLogout();
        }
      },

      handleLogout() {
        axios.post('/pms/user/logout').then(response => {
          if (response.data.success) {
            this.$message.success(response.data.message);
            localStorage.removeItem('currentUser');
            window.location.href = 'login.html';
          }
        }).catch(error => {
          console.error('退出登录失败:', error);
        });
      },

      formatRole(role) {
        const roleMap = { 'admin': '管理员', 'sales': '销售员', 'inventory': '库存管理员' };
        return roleMap[role] || role;
      },

      formatDate(dateString) {
        if (!dateString) return '';
        return new Date(dateString).toLocaleString();
      }
    }
  });
</script>
</body>
</html>